"""
Flask Web应用模块

提供基于Flask的Web服务，监听7777端口。
"""
from flask import Flask, jsonify
from src.config import GlobalConfig
from src.utils.api_utils import ApiClient
from src.utils.prompt_utils import generate_complete_prompt
from src.utils.context_loader import ContextLoader
from src.utils.block_utils import BlockExtractor
from src.utils.runtime_state import RuntimeState
import os
import json

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

def decode_request_data(raw_data):
    # 尝试不同的编码方式
    encodings = ['utf-8', 'gbk', 'gb2312', 'iso-8859-1']
    data = None
    
    for encoding in encodings:
        try:
            if isinstance(raw_data, bytes):
                decoded_data = raw_data.decode(encoding)
            else:
                decoded_data = raw_data
            data = json.loads(decoded_data)
            print(f"Successfully decoded with {encoding}")
            break
        except Exception as e:
            print(f"Failed to decode with {encoding}: {str(e)}")
            continue
            
    return data

@app.after_request
def after_request(response):
    response.headers['Content-Type'] = 'application/json; charset=utf-8'
    return response

@app.route('/')
def index():
    """首页路由"""
    return jsonify({
        "status": "running",
        "message": "Flask Web服务已启动"
    })

@app.route('/api/file/content', methods=['GET'])
def get_file_content():
    """
    获取指定文件的内容
    
    Query参数:
        path: 文件路径（必选）
        
    Returns:
        JSON格式的响应:
        {
            "status": "success",
            "content": "文件内容"
        }
        
    错误响应:
        {
            "status": "error",
            "message": "错误信息"
        }
    """
    from flask import request
    
    try:
        # 获取文件路径参数
        file_path = request.args.get('path')
        if not file_path:
            return jsonify({
                "status": "error",
                "message": "缺少必选参数: path"
            }), 400
            
        # 获取工作目录
        work_dir = GlobalConfig.get_work_dir()
        if not work_dir:
            return jsonify({
                "status": "error",
                "message": "工作目录未设置"
            }), 400
            
        # 拼接完整文件路径
        full_path = os.path.join(work_dir, file_path)
        
        # 检查文件是否存在
        if not os.path.exists(full_path):
            return jsonify({
                "status": "error",
                "message": f"文件不存在: {file_path}"
            }), 404
            
        # 检查是否是文件
        if not os.path.isfile(full_path):
            return jsonify({
                "status": "error",
                "message": f"路径不是文件: {file_path}"
            }), 400
            
        # 读取文件内容
        try:
            with open(full_path, 'r', encoding='utf-8') as f:
                content = f.read()
        except UnicodeDecodeError:
            return jsonify({
                "status": "error",
                "message": f"文件编码不是UTF-8: {file_path}"
            }), 400
            
        return jsonify({
            "status": "success",
            "content": content
        })
        
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500

@app.route('/api/command', methods=['POST'])
def execute_command():
    """
    执行命令行命令
    
    请求体参数:
        command: 要执行的命令字符串（必选）
        
    Returns:
        JSON格式的响应:
        {
            "status": "success",
            "msg": "命令执行结果"
        }
        
    错误响应:
        {
            "status": "error",
            "message": "错误信息"
        }
    """
    from flask import request
    
    try:
        # 获取并解码请求数据
        data = decode_request_data(request.get_data())
        if not data:
            return jsonify({
                "status": "error",
                "message": "无法解析请求数据"
            }), 400
            
        # 获取命令参数
        command = data.get('command')
        if not command:
            return jsonify({
                "status": "error",
                "message": "缺少必选参数: command"
            }), 400
        
        if command.strip() == 'exit':
            return jsonify({
                "status": "success",
                "msg": "exit not supported"
            })
        
        # 获取CLI实例并执行命令
        cli = GlobalConfig.get_cli()
        GlobalConfig.set_result(None)
        result = cli._process_command(command)
        if result:
            return jsonify({
                "status": "success",
                "msg": GlobalConfig.get_result()
            })
        else:
            return jsonify({
                "status": "error",
                "message": "命令执行失败"
            }), 500
        
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500

@app.route('/api/files', methods=['GET'])
def get_files():
    """
    获取工作目录下的所有文件路径
    
    Returns:
        JSON格式的响应:
        {
            "work_dir": "工作目录路径",
            "files": ["文件1全路径", "文件2全路径", ...]
        }
    """
    try:
        # 获取工作目录
        work_dir = GlobalConfig.get_work_dir()
        if not work_dir:
            return jsonify({
                "status": "error",
                "message": "工作目录未设置"
            }), 400

        # 获取所有文件路径
        relative_paths = ContextLoader.collect_paths(work_dir)
        
        # 转换为绝对路径
        absolute_paths = [os.path.join(work_dir, path) for path in relative_paths]
        
        return jsonify({
            "status": "success",
            "work_dir": work_dir,
            "files": absolute_paths
        })
        
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500

def run_web_server():
    """启动Web服务器"""
    app.run(host='0.0.0.0', port=7777) 